//
//  gwchaxunViewController.m
//  tongxiangOASystem
//
//  Created by michael on 17/4/11.
//  Copyright © 2017年 czd. All rights reserved.
//
#import "FBMCombox.h"
#import "LGLSearchBar.h"
#import "ckUnDonelistCell.h"
#import "gwchaxunViewController.h"
#import "SQMenuShowView.h"
#define KShowYearsCount 100
@interface gwchaxunViewController ()<FBMComboxDelegate>

@property (nonatomic, strong) NSArray *yearArray;
@property (nonatomic, assign) NSInteger year;

@property (strong, nonatomic)  SQMenuShowView *showView;
@property (assign, nonatomic)  BOOL  isShow;
@property (strong, nonatomic)  SQMenuShowView *showView2;
@property (assign, nonatomic)  BOOL  isShow2;
@property(nonatomic,strong)NSMutableArray * dataArray;
@property(nonatomic,assign)NSInteger totalCounts; //总条数
@property(nonatomic,assign)NSInteger currentPage; //当前页
@property(nonatomic,assign)BOOL isSearching;
@property(nonatomic,strong)NSString * searchText;
@property (nonatomic, strong) HWOptionButton *yearBtn;
@property (nonatomic, strong) HWOptionButton *yearBtn2;
@property(nonatomic,strong)NSDictionary * adic;

@end

@implementation gwchaxunViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"文件查询";

     NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute fromDate:[NSDate date]];
    _year = [components year];
 NSInteger firstYear = _year - KShowYearsCount / 2;
    NSMutableArray *yearArray = [NSMutableArray array];
    for (int i = 0; i < KShowYearsCount; i++) {
        [yearArray addObject:[NSString stringWithFormat:@"%ld", firstYear + i]];
    }
    _yearArray = yearArray;
            self.automaticallyAdjustsScrollViewInsets = NO;

    self.view.backgroundColor = [UIColor whiteColor];
              UIColor *myColor = [UIColor colorWithWhite:0.5 alpha:0.2];
              _bgview = [[UIView alloc]initWithFrame:self.view.frame];
              _bgview.backgroundColor = myColor;
              [self.view addSubview:_bgview];
              [self _iniview];
                 __weak typeof(self) weakSelf = self;

              [self.tableView addHeaderWithCallback:^{
        weakSelf.currentPage = 1;

        [weakSelf loadData]; //加载网络数据
    }];
    [self.tableView headerBeginRefreshing];
    
    [self.tableView addFooterWithCallback:^{
        if ((self.currentPage - 1)*KPageSize < self.totalCounts ){
        if (weakSelf.isSearching) {
    [weakSelf loadsearchMore];
}
    else    {
             [weakSelf loadMore];
             }
        }else{
        
            [weakSelf.tableView footerEndRefreshing];
            [weakSelf.view makeToast:@"没有更多了"];
    
        }
       
    }];
    


    // Do any additional setup after loading the view.
}
- (void)_iniview{
float width = (kScreenWidth-30);
_label1 = [[UILabel alloc]initWithFrame:CGRectMake(10,10, width-40, 30)];
 _label1.backgroundColor = [UIColor whiteColor];
    _label1.text = [NSString stringWithFormat:@"%ld",
                    (long)_year];


//[self.bgview addSubview:_label1];

  //搜索框
     LGLSearchBar * searchBar = [[LGLSearchBar alloc] initWithFrame:CGRectMake(10,10+30, kScreenWidth-20 , 40) searchBarStyle:LGLSearchBarStyleDefault];
     UIColor *textColor = self.view.tintColor;
     searchBar.tintColor = textColor;

    searchBar.barBackgroudColor = textColor;
                  UIColor *myColor = [UIColor colorWithWhite:0.5 alpha:0.2];
//     searchBar.textBordStyle = LGLTextBorderStyleNoine;

  [searchBar setSearchBarBordeWidth:2 bordColor:textColor bordRadius:5];
    [searchBar searchBarTextSearchTextBlock:^(NSString *searchText) {
        NSLog(@"%@", searchText);
        if (!searchText) {
    [self.bgview makeToast:@"请输入关键字"];
}
        [self.view endEditing:YES];
         self.isSearching = YES;
        _searchText = searchText;
    [self loadSearchData:_searchText];

        
    }];
//    [self.bgview addSubview:searchBar];
    
   
       //年份按钮
    _yearBtn = [[HWOptionButton alloc] initWithFrame:CGRectMake(_label1.right, _label1.top, 40, 30)];
    _yearBtn.array = _yearArray;
    _yearBtn.title = [NSString stringWithFormat:@"%ld",
                    (long)_year];

    _yearBtn.row = KShowYearsCount / 2;
    _yearBtn.delegate = self;
//    [self.bgview addSubview:_yearBtn];
    

//-30-10-40
 _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, KScreenHeight-LL_StatusBarAndNavigationBarHeight) style:UITableViewStylePlain];
         self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
//_tableView.backgroundColor = [UIColor yellowColor];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    
    
    [self.view addSubview:_tableView];
     
     FBMCombox *combox = [[FBMCombox alloc] initWithItems:_yearArray withFrame:CGRectMake(10,64+10, width-40, 30)];
    combox.delegate = self;
//    [self.bgview addSubview:combox];

   _showView = [[SQMenuShowView alloc]initWithFrame:CGRectMake(_label1.left, _label1.bottom, 100, 200)  items:_yearArray showPoint:CGPointMake(_label1.left+25, _label1.bottom)];
    _showView.sq_backGroundColor = [UIColor whiteColor];
    [self.bgview addSubview:_showView];
  __weak typeof(self) weakSelf = self;
    [self.showView selectBlock:^(SQMenuShowView *view, NSInteger index) {
        weakSelf.isShow = YES;
        _label1.text = [NSString stringWithFormat:@"点击第%ld个item",index+1];
        NSLog(@"点击第%ld个item",index+1);
    }];
    
    _label2 = [[UILabel alloc]initWithFrame:CGRectMake(_button1.right+10,64+10, width-40, 30)];
 _label2.backgroundColor = [UIColor whiteColor];

//[self.bgview addSubview:_label2];
   //年份按钮
    _yearBtn2 = [[HWOptionButton alloc] initWithFrame:CGRectMake(_label2.right, _label1.top, 40, 30)];
    _yearBtn2.array = @[@"item1",@"item2",@"item3",@"item4",@"item5",@"item5",@"item5",@"item5",@"item5",@"item5"];
    
    _yearBtn2.row = @[@"item1",@"item2",@"item3",@"item4",@"item5",@"item5",@"item5",@"item5",@"item5",@"item5"].count / 2;
    _yearBtn2.delegate = self;
//    [self.bgview addSubview:_yearBtn2];


_button2 = [UIButton buttonWithType:UIButtonTypeCustom];
_button2.frame = CGRectMake(_label2.right, _label1.top, 40, 30);
 _button2.backgroundColor = [UIColor whiteColor];
[_button2 setBackgroundImage:[UIImage imageNamed:@"下箭头"] forState:UIControlStateNormal];
 [_button2 addTarget:self action:@selector(buttonAction2)forControlEvents:UIControlEventTouchUpInside];
//[self.bgview addSubview:_button2];

   _showView2 = [[SQMenuShowView alloc]initWithFrame:CGRectMake(_label2.left, _label2.bottom, 100, 0)  items:@[@"item1",@"item2",@"item3",@"item4",@"item5",@"item5",@"item5",@"item5",@"item5",@"item5"]showPoint:CGPointMake(_label2.left+25, _label2.bottom)];
    _showView2.sq_backGroundColor = [UIColor whiteColor];
    [self.bgview addSubview:_showView2];
    [self.showView2 selectBlock:^(SQMenuShowView *view, NSInteger index) {
        weakSelf.isShow2 = NO;
        _label2.text = [NSString stringWithFormat:@"点击第%ld个item",index+1];
        NSLog(@"点击第%ld个item",index+1);
    }];
  
    
   

    
    
}
-(void)loadSearchData:(NSString*)Searchtext{
    __weak typeof(self) weakSelf = self;
        NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
_currentPage = 1;
    NSArray * array = @[@{@"dbpath": _label1.text
},@{@"condition":Searchtext},@{@"userId":userId},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
NSLog(@"%@",array);
 [HttpTools requestWithURL:KexexchSearchURL arrays:array method:@"ArchiveYearSearch" success:^(id JSON) {
  if (self.currentPage ==1) {
            [self.dataArray removeAllObjects];
        }
        _adic= JSON[@"display"];

      _dataArray =   [NSMutableArray array];
        NSArray *array = JSON[@"data"];
  self.totalCounts =[JSON[@"number"] intValue];

if(JSON[@"number"]){

       self.title = [NSString stringWithFormat:@"公文查询(%@)",JSON[@"number"] ];}

       else{

       self.title = @"公文查询";
       }         for (NSDictionary *dic in array) {
    NSDictionary *dict = dic;
    [_dataArray addObject:dict];
    
}
if (self.dataArray.count ==0) {
            [self.view makeToast:@"暂时还没数据哦"];
        }
        [weakSelf.tableView footerEndRefreshing];
        [weakSelf.tableView reloadData];
        weakSelf.currentPage++;
        
        if (self.tableView.headerRefreshing) {
            [self.tableView headerEndRefreshing];
        }
        if (self.tableView.footerRefreshing) {
            [self.tableView footerEndRefreshing];
        }
        
    } failure:^(NSError *error) {
        if (self.tableView.headerRefreshing) {
            [self.tableView headerEndRefreshing];
        }
        if (self.tableView.footerRefreshing) {
            [self.tableView footerEndRefreshing];
        }
    }];
    




}
- (void)loadsearchMore{
    __weak typeof(self) weakSelf = self;
        NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];

    NSArray * array = @[@{@"dbpath": [NSString stringWithFormat:@"%ld",
                    (long)_year]
},@{@"userId":userId},@{@"condition":_searchText},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];

 [HttpTools requestWithURL:KexexchSearchURL arrays:array method:@"ArchiveYearSearch" success:^(id JSON) {
                NSArray *array = JSON[@"data"];

 for (NSDictionary *dic in array) {
    NSDictionary *dict = dic;
    [_dataArray addObject:dict];
    
}
_adic= JSON[@"display"];
//        self.totalCounts =[JSON[@"number"] intValue];
//
//       self.title = [NSString stringWithFormat:@"公文查询(%@)",JSON[@"number"] ];
    self.currentPage++;
        [self.tableView footerEndRefreshing];
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        if (self.tableView.headerRefreshing) {
            [self.tableView headerEndRefreshing];
        }
        if (self.tableView.footerRefreshing) {
            [self.tableView footerEndRefreshing];
        }
    }];
    




}
- (void)didSelectOptionInHWOptionButton:(HWOptionButton *)optionButton
{
if ((optionButton = _yearBtn)) {

    _label1.text = optionButton.title;


}if ((optionButton = _yearBtn2)) {
    _label2.text = optionButton.title;

}
   }

#pragma mark 加载网络数据
-(void)loadData{
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"userId":userId},@{@"dbpath":[NSString stringWithFormat:@"%ld",_year]},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
    [HttpTools requestWithURL:KexexcharchiveURL arrays:array method:@"archiveFilePage"success:^(id JSON) {
    NSLog(@"%@",JSON);
        if (self.currentPage ==1) {
            [self.dataArray removeAllObjects];
        }
      _dataArray =   [NSMutableArray array];
        NSArray *array = JSON[@"data"];
         self.totalCounts =1000;

//       self.title = [NSString stringWithFormat:@"公文查询(%@)",JSON[@"number"] ];

         for (NSDictionary *dic in array) {
    NSDictionary *dict = dic;
    [_dataArray addObject:dict];
    
}
_adic= JSON[@"display"];

        [self.tableView reloadData];
        [self.tableView headerEndRefreshing];
        self.currentPage++;
        if (self.dataArray.count ==0) {
            [self.view makeToast:@"暂时还没数据哦"];
        }
    } failure:^(NSError *error) {
        [self.tableView headerEndRefreshing];
    }];
    
}

#pragma mark 加载更多
-(void)loadMore{
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
//        NSArray * array = @[@{@"userId":userId},@{@"dbpath":[NSString stringWithFormat:@"%ld",_year]},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];

    NSArray * array = @[@{@"userId":userId},@{@"dbpath":[NSString stringWithFormat:@"%ld",_year]},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
    [HttpTools requestWithURL:KexexcharchiveURL arrays:array method:@"archiveFilePage" success:^(id JSON) {
                NSArray *array = JSON[@"data"];

 for (NSDictionary *dic in array) {
    NSDictionary *dict = dic;
    [_dataArray addObject:dict];
    
}
//_adic= JSON[@"display"];

//       self.title = [NSString stringWithFormat:@"公文查询(%lu)",(unsigned long)[array count]];
    self.currentPage++;
        [self.tableView footerEndRefreshing];
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        [self.tableView footerEndRefreshing];
    }];
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//    UnDoneModel * model = self.dataArray[indexPath.row];
//    CGFloat height = 0;
//    CGFloat  titlesize  = [OAToolBox sizebyText:model.title font:14 minsWidth:80];
//    
//    NSString * desstring = [NSString stringWithFormat:@"%@",model.time];
//    CGFloat dessize = [OAToolBox sizebyText:desstring font:13 minsWidth:40];;
//    height = titlesize + dessize + 20;
//    return  height;
    NSDictionary *dic = self.dataArray[indexPath.row];

    CGFloat  titleFloat  = [OAToolBox sizebyText:dic[@"subject"] font:15 minsWidth:60];

    return  titleFloat  +75+10;
}




#pragma mark UITableView dataScource
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
 static NSString *CellIdentifier = @"Cell";  

    ckUnDonelistCell *cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
  if (cell==nil) {  
        cell=[[ckUnDonelistCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    
 NSDictionary *dic = self.dataArray[indexPath.row];
    cell.dic = dic;
    cell.adic = _adic;
    cell.number = [NSString stringWithFormat:@"%ld",(long)indexPath.row+1];
    return cell;




//    OAUnDoneListCell * cell = [OAUnDoneListCell cellWithTableView:tableView];
//    UnDoneModel * model = self.dataArray[indexPath.row];
//    cell.model = model;
//    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

      UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];

    [tableView deselectRowAtIndexPath:indexPath animated:YES];
        NSDictionary *dic = self.dataArray[indexPath.row];

     UnDoneModel * model = self.dataArray[indexPath.row];
     detailViewController * detailVC = (detailViewController *)[storyBoard instantiateViewControllerWithIdentifier:@"detail"];
detailVC.fileId = dic[@"unid"];
detailVC.type = @"chaxun";
detailVC.year =  _label1.text;

[self.navigationController pushViewController:detailVC animated:YES];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}
- (void)buttonAction1{

 _isShow = !_isShow;
    
    if (_isShow) {
        [self.showView showView];

    }else{
        [self.showView dismissView];
    }
    


 }
 - (void)buttonAction2{

 _isShow2 = !_isShow2;
    
    if (_isShow2) {
        [self.showView2 showView];

    }else{
        [self.showView2 dismissView];
    }
    


 }
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
